package m.jclecai.com.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.squareup.okhttp.Request;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import m.jclecai.com.R;
import m.jclecai.com.activity.WebHelperActivity;
import m.jclecai.com.adapter.klsfRecyclerAdapter.HistoryAdapter;
import m.jclecai.com.adapter.klsfRecyclerAdapter.MyBallAdapter;
import m.jclecai.com.base.digitalLottery.DefaultDigitalLotteryActivity;
import m.jclecai.com.bean.IssueInfoBean;
import m.jclecai.com.bean.MissDataBean;
import m.jclecai.com.bean.common.BettingBean;
import m.jclecai.com.constant.Constant_Result;
import m.jclecai.com.constant.Constant_Url;
import m.jclecai.com.pop.GuideMenuPopupWindow;
import m.jclecai.com.pop.KLSFPopWindow;
import m.jclecai.com.presenter.lottery.KLSFPresenter;
import m.jclecai.com.utils.BaseUtils;
import m.jclecai.com.utils.KlpkUtils;
import m.jclecai.com.utils.MakeRandomUtil;
import m.jclecai.com.utils.PreferenceUtil;
import m.jclecai.com.utils.ShakeUtils;
import m.jclecai.com.utils.http.FastOk;
import m.jclecai.com.utils.http.HttpManager;
import m.jclecai.com.view.common.BallView;

public class BettingKLSFActivity extends DefaultDigitalLotteryActivity {


    @BindView(R.id.tv_hint)
    TextView mTvHint;

    @BindView(R.id.iv_shake)
    ImageView mIvShake;

    @BindView(R.id.tv_position_one)
    TextView mTvPositionOne;

    @BindView(R.id.rv_item_one)
    RecyclerView mRvItemOne;

    @BindView(R.id.ll_item_one)
    LinearLayout mLlItemOne;

    @BindView(R.id.tv_position_two)
    TextView mTvPositionTwo;

    @BindView(R.id.rv_item_two)
    RecyclerView mRvItemTwo;

    @BindView(R.id.ll_item_two)
    LinearLayout mLlItemTwo;

    @BindView(R.id.line_one)
    RelativeLayout mLineOne;

    private GridLayoutManager mItemOneGridLayout;
    private GridLayoutManager mItemTwoGridLayout;
    private MyBallAdapter mItemOneBallAdapter;
    private MyBallAdapter mItemTwoBallAdapter;
    private LinearLayoutManager mHistoryLayoutManager;
    private HistoryAdapter mHistoryAdapter;
    private String mType;
    private KLSFPopWindow mCenterPopWindow;

    public String[] mCenterPopupData = {"选一数投", "选一红投", "任选二", "任选三", "任选四", "任选五", "选二连组", "选二连直"};

    public int mCurrentMode = 0;
    private List<String> mListData20;
    private List<String> mListData18;
    private List<String> mListData2;
    private String[] mM0 = new String[0];
    private String[] mM1 = new String[0];
    private String[] mM2 = new String[0];
    private String[] mM3 = new String[0];
    private String[] mM4 = new String[0];
    private GuideMenuPopupWindow mRightMenuPopupWindow;

    public List<BettingBean> mBetList = new ArrayList<>();

    /**
     * 业务逻辑类；
     */
    private KLSFPresenter mKLSFPresenter;
    private ShakeUtils mShakeUtils;

    @Override
    protected int getContentRes() {
        return R.layout.activity_betting_klsf;
    }


    @Override
    protected void initView() {
        super.initView();

        mKLSFPresenter = new KLSFPresenter(this);

        initHeadView();

        initItemOne();
        initItemTwo();
        initHistory();
        initPopupWindow();
    }

    @Override
    protected void initData() {
        super.initData();

        mShakeUtils = new ShakeUtils(this);

        mShakeUtils.setOnShakeUtilsListener(new ShakeUtils.OnShakeUtilsListener() {
            @Override
            public void onShakedListener() {
                randomSelected();
            }

            @Override
            public void hasNotVibratorListener() {

            }
        });
        //mType = getIntent().getStringExtra("type");
        mType="gdklsf";
        initBallData();
        initPopupWindowData();

        refreshUI();
        requestMissData(mType);
        requestIssueInfo(mType);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mShakeUtils.register();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mShakeUtils.unRegister();
    }

    @Override
    protected void initListener() {
        super.initListener();
        mItemOneBallAdapter.setOnBallCheckedListener(new MyBallAdapter.OnBallCheckedListener() {
            @Override
            public void onBallChecked(BallView view, Boolean isChecked) {
                onItemOneBallsClick(view, isChecked);
            }
        });
        mItemTwoBallAdapter.setOnBallCheckedListener(new MyBallAdapter.OnBallCheckedListener() {
            @Override
            public void onBallChecked(BallView view, Boolean isChecked) {
                //这里我们将执行的逻辑是判断是否符合了成为一注的条件；
                onItemTwoBallsClick(view, isChecked);
            }
        });

        mIvShake.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                randomSelected();
            }
        });
    }

    /**
     * 第一个条目的小球被点击的时候会触发这个方法；
     *
     * @param view      点击的第一个条目的那个小球；
     * @param isChecked 这个小球的状态；
     */
    private void onItemOneBallsClick(BallView view, Boolean isChecked) {

        setNumberMoney();
    }

    private void setNumberMoney() {
        boolean isShow = false;       //是否显示条目；
        Set<Map.Entry<String, Boolean>> itemOneEntries = mItemOneBallAdapter.getSelectBalls().entrySet();
        int oneSelectBallCount = 0;  //条目一选中小球的数量；

        for (Map.Entry<String, Boolean> entry : itemOneEntries) {
            if (entry.getValue()) {
                //这里表示有选中的；
                oneSelectBallCount++;
                removeBallSelected(entry.getKey(), mItemTwoGridLayout);

                setBottomBarLeftText("清空");
            }
        }
        if(oneSelectBallCount==0){
            setBottomBarLeftText("机选");
            mTvNumberMoney.setVisibility(View.GONE);
            return;
        }

        Set<Map.Entry<String, Boolean>> itemTwoEntries = mItemTwoBallAdapter.getSelectBalls().entrySet();
        int twoSelectBallCount = 0;  //条目二选中小球的数量；

        for (Map.Entry<String, Boolean> itemTwoEntry : itemTwoEntries) {
            if (itemTwoEntry.getValue()) {
                twoSelectBallCount++;       //条目二有多少个小球被选中；
            }
        }


        int betNum = 0;  //注数
        switch (mCurrentMode) {
            case 0: //选一数投
            case 1: //选一红投
                if (oneSelectBallCount > 0) {
                    //这里我们要做的一个操作就是该变title;
                    isShow = true;
                    betNum = oneSelectBallCount;
                }
                break;
            case 2: //任选二
                if (oneSelectBallCount > 1) {
                    isShow = true;
                    betNum = BaseUtils.math2(oneSelectBallCount, 2);
                }
                break;
            case 3: //任选三
                if (oneSelectBallCount > 2) {
                    isShow = true;
                    betNum = BaseUtils.math2(oneSelectBallCount, 3);
                }
                break;
            case 4: //任选四
                if (oneSelectBallCount > 3) {
                    isShow = true;
                    betNum = BaseUtils.math2(oneSelectBallCount, 4);
                }
                break;
            case 5: //任选五
                if (oneSelectBallCount > 4) {
                    isShow = true;
                    betNum = BaseUtils.math2(oneSelectBallCount, 5);
                }
                break;
            case 6: //选二连组
                if (oneSelectBallCount > 1) {
                    isShow = true;
                    betNum = BaseUtils.math2(oneSelectBallCount, 2);
                }
                break;
            case 7: //选二直选；
                if (oneSelectBallCount > 0 && twoSelectBallCount > 0) {
                    isShow = true;
                    betNum = oneSelectBallCount * twoSelectBallCount;
                }
                break;
        }
        mTvNumberMoney.setVisibility(isShow ? View.VISIBLE : View.GONE);
        mTvNumberMoney.setText(betNum + "注 , " + betNum * 2 + "元");
    }

    /**
     * 第二个条目的小球被点击的时候会触发这个方法；
     *
     * @param view      点击第二个条目的哪个小球
     * @param isChecked 这个小球的状态；
     */
    private void onItemTwoBallsClick(BallView view, Boolean isChecked) {


        //这里只有选二直连才可能触发这个方法；===这里是连二直选的逻辑===
        boolean isShow = false;       //是否显示条目；
        int oneItemSelectBallCount = 0;  //条目一选中小球的数量；
        int twoItemSelectBallCount = 0;  //条目二选中小球的数量；
        int betNum = 0;

        Set<Map.Entry<String, Boolean>> itemTwoEntries = mItemTwoBallAdapter.getSelectBalls().entrySet();
        for (Map.Entry<String, Boolean> itemTwoEntry : itemTwoEntries) {

            if (itemTwoEntry.getValue()) {
                //这里表示itemTwo选中的小球的数量；
                twoItemSelectBallCount++;
                //去掉itemOne中出现的相同的并且已经被选中的；
                removeBallSelected(itemTwoEntry.getKey(), mItemOneGridLayout);

                setBottomBarLeftText("清空");
            }
        }
        if (twoItemSelectBallCount==0) {
            setBottomBarLeftText("机选");
            mTvNumberMoney.setVisibility(View.GONE);
            return;
        }

        Set<Map.Entry<String, Boolean>> itemOneEntries = mItemOneBallAdapter.getSelectBalls().entrySet();
        for (Map.Entry<String, Boolean> itemOneEntry : itemOneEntries) {
            if (itemOneEntry.getValue()) {
                //表示itemOne选中小球的数量；
                oneItemSelectBallCount++;
            }
        }

        if (oneItemSelectBallCount > 0 && twoItemSelectBallCount > 0) {
            //这里表示才够一注
            isShow = true;
            //这里我们要设置多少注；
            betNum = oneItemSelectBallCount * twoItemSelectBallCount;
            mTvNumberMoney.setText(betNum + "注 , " + betNum * 2 + "元");
        }

        mTvNumberMoney.setVisibility(isShow ? View.VISIBLE : View.GONE);
    }

    /**
     * 取消小球的选中状态
     *
     * @param ballNumber
     * @param layoutManager
     */
    public void removeBallSelected(String ballNumber, RecyclerView.LayoutManager layoutManager) {

        for (int i = 0; i < layoutManager.getChildCount(); i++) {
            View view = layoutManager.findViewByPosition(i);
            BallView ballView = (BallView) view.findViewById(R.id.bv_ball_view);
            if (ballView.getNumber().equals(ballNumber)) {
                ballView.setChecked(false);
                return;
            }
        }
    }

    /**
     * 标题栏的一些设置；
     */
    private void initHeadView() {
        setTitle("选一数投", R.drawable.gs);
        leftOptionText("返回");
        rightOptionText("", R.drawable.action_menu);
        tvMidTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //titlle的点击事件；
                startAnimation(ivTitleIcon, R.anim.rotate_0_180);
                mCenterPopWindow.showAsDropDown(rlBar);
            }
        });

        tvRightOption.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //这里我们是需要要显示
                mRightMenuPopupWindow.showAsDropDown(tvRightOption);
            }
        });
    }

    private void initPopupWindow() {
        initCenterPopupWindow();
        initRightPopupWindow();
    }

    private void initRightPopupWindow() {
        mRightMenuPopupWindow = new GuideMenuPopupWindow(this);

        String title = "";
        if (PreferenceUtil.isShowMissing(this)) {
            title = "隐藏遗漏";
            showMissData(true);
        } else {
            title = "显示遗漏";
            showMissData(false);
        }

        mRightMenuPopupWindow.addItem(title, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean showMissing = PreferenceUtil.isShowMissing(BettingKLSFActivity.this);
                boolean isShowMiss = !showMissing;

                if (isShowMiss) {
                    mRightMenuPopupWindow.setTitle(0, "隐藏遗漏");
                    showMissData(true);
                } else {
                    mRightMenuPopupWindow.setTitle(0, "显示遗漏");
                    showMissData(false);
                }
                PreferenceUtil.setIsShowMissing(BettingKLSFActivity.this, isShowMiss);

                mRightMenuPopupWindow.dismiss();
            }
        });
        mRightMenuPopupWindow.addItem("历史开奖", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到开奖
                Intent intent = new Intent(BettingKLSFActivity.this, LotteryHistoryActivity.class);
                intent.putExtra("type", mType);
                startActivity(intent);
            }
        });
        mRightMenuPopupWindow.addItem("玩法介绍", new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent helpIntent = new Intent(BettingKLSFActivity.this, WebHelperActivity.class);
                helpIntent.putExtra("title", "玩法介绍");
                helpIntent.putExtra("code", "gdklsf");
                helpIntent.putExtra("isLocal", true);
                startActivity(helpIntent);
            }
        });
    }

    private void showMissData(boolean isShow) {
        mItemOneBallAdapter.setShowMissData(isShow);
        mItemTwoBallAdapter.setShowMissData(isShow);
    }

    private void initCenterPopupWindow() {
        mCenterPopWindow = new KLSFPopWindow(this);
        mCenterPopWindow.setOnItemClickListener(new KLSFPopWindow.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                //这里我们执行的逻辑就是根据相应的position显示具体的界面；
                mCurrentMode = position;
                refreshUI();
            }
        });
        mCenterPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                startAnimation(ivTitleIcon, R.anim.rotate_180_360);
            }
        });
    }

    /**
     * 这方法会根据不同的玩法显示不同的ui界面；
     */
    private void refreshUI() {
        switch (mCurrentMode) {
            case 0:
                //选一数投
                onCenterPopPositionOneClick();
                break;
            case 1:
                //选一红投
                onCenterPopPositionTwoClick();
                break;
            case 2:
                //任选二
                onCenterPopPositionThreeClick();
                break;
            case 3:
                //任选三
                onCenterPopPositionFourClick();
                break;
            case 4:
                //任选四
                onCenterPopPositionFiveClick();
                break;
            case 5:
                //任选五
                onCenterPopPositionSixClick();
                break;
            case 6:
                //选二连组
                onCenterPopPositionSevenClick();
                break;
            case 7:
                //选二直连
                onCenterPopPositionEightClick();
                break;
        }
    }

    /**
     * 选二连组
     */
    public void onCenterPopPositionSevenClick() {
        showItemOneListData20();

        setTitle(mCenterPopupData[6]);  //设置标题界面
        mTvHint.setText("至少选2个号码，猜中任意连续2位奖金31元");
        mTvPositionOne.setText("选号");

        mItemOneBallAdapter.refreshMissData(mM4);

        clearAllBallStatue();
    }

    /**
     * 选二直连
     */
    public void onCenterPopPositionEightClick() {
        showItemOneAndTwo20();

        setTitle(mCenterPopupData[7]);  //设置标题界面
        mTvHint.setText("每位至少选1个号码，按位猜中任意连续2位奖金320元");
        mTvPositionOne.setText("前位");
        mTvPositionTwo.setText("后位");

        mItemOneBallAdapter.refreshMissData(mM2);
        mItemTwoBallAdapter.refreshMissData(mM3);
        clearAllBallStatue();
    }

    /**
     * 任选五
     */
    public void onCenterPopPositionSixClick() {
        showItemOneListData20();
        setTitle(mCenterPopupData[5]);  //设置标题界面
        mTvHint.setText("至少选5个号码，猜中任意5位奖金320元");
        mTvPositionOne.setText("选号");

        mItemOneBallAdapter.refreshMissData(mM4);  //设置遗漏
        clearAllBallStatue();
    }

    /**
     * 任选四
     */
    public void onCenterPopPositionFiveClick() {

        showItemOneListData20();
        setTitle(mCenterPopupData[4]);  //设置标题界面
        mTvHint.setText("至少选4个号码，猜中任意4位奖金80元");
        mTvPositionOne.setText("选号");


        mItemOneBallAdapter.refreshMissData(mM4);  //设置遗漏
        clearAllBallStatue();
    }

    /**
     * 任选三
     */
    public void onCenterPopPositionFourClick() {
        showItemOneListData20();
        setTitle(mCenterPopupData[3]);  //设置标题界面
        mTvHint.setText("至少选3个号码，猜中任意3位奖金24元");
        mTvPositionOne.setText("选号");

        mItemOneBallAdapter.refreshMissData(mM4);  //设置遗漏

        clearAllBallStatue();
    }

    /**
     * 任选二
     */
    public void onCenterPopPositionThreeClick() {


        showItemOneListData20();
        setTitle(mCenterPopupData[2]);  //设置标题界面
        mTvHint.setText("至少选2个号码，猜中任意2位奖金8元");
        mTvPositionOne.setText("选号");

        mItemOneBallAdapter.refreshMissData(mM4);  //设置遗漏

        clearAllBallStatue();
    }

    /**
     * 选一红投
     */
    public void onCenterPopPositionTwoClick() {

        showItemOneListData2();
        setTitle(mCenterPopupData[1]);  //设置标题界面
        mTvHint.setText("第1位是19或20，奖金5元");
        mTvPositionOne.setText("选号");
        mItemOneBallAdapter.refreshMissData(mM1);   //设置遗漏

        clearAllBallStatue();
    }

    /**
     * 中间的popupWindow第一个条目被点击，也就是选一数投
     */
    public void onCenterPopPositionOneClick() {

        showItemOneListData18();    //设置桌面界面；
        setTitle(mCenterPopupData[0]);  //设置标题界面
        mTvHint.setText("猜中第1位，奖金25元");
        mTvPositionOne.setText("选号");
        mItemOneBallAdapter.refreshMissData(mM0);    //设置遗漏

        clearAllBallStatue();
    }

    public void clearAllBallStatue(RecyclerView.LayoutManager layoutManager) {

        for (int i = 0; i < layoutManager.getChildCount(); i++) {
            View view = layoutManager.findViewByPosition(i);
            BallView ballView = (BallView) view.findViewById(R.id.bv_ball_view);
            ballView.setChecked(false);
        }
    }

    public void clearAllBallStatue() {
        clearAllBallStatue(mItemOneGridLayout);
        clearAllBallStatue(mItemTwoGridLayout);
    }

    /**
     * 这里表示的意思是是显示第一个条目，并且数目是01到18
     */
    public void showItemOneListData18() {
        mItemOneBallAdapter.refresh(mListData18);
        mLlItemTwo.setVisibility(View.GONE);
        mLineOne.setVisibility(View.GONE);
    }

    public void showItemOneListData20() {
        mItemOneBallAdapter.refresh(mListData20);
        mLlItemTwo.setVisibility(View.GONE);
        mLineOne.setVisibility(View.GONE);
    }

    public void showItemOneListData2() {
        mItemOneBallAdapter.refresh(mListData2);
        mLlItemTwo.setVisibility(View.GONE);
        mLineOne.setVisibility(View.GONE);
    }

    /**
     * itemOne和itemTwo都是从01，到20的；
     */
    public void showItemOneAndTwo20() {
        mLlItemOne.setVisibility(View.VISIBLE);
        mLlItemTwo.setVisibility(View.VISIBLE);
        mLineOne.setVisibility(View.VISIBLE);

        mItemOneBallAdapter.refresh(mListData20);
        mItemTwoBallAdapter.refresh(mListData20);
    }


    private void initHistory() {
        //这里我们要做的一个操作就是对historyRecyclerView进行一个初始化；
        mHistoryLayoutManager = new LinearLayoutManager(this) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        mRvHistory.setLayoutManager(mHistoryLayoutManager);
        mHistoryAdapter = new HistoryAdapter(null);
        mRvHistory.setAdapter(mHistoryAdapter);
    }

    private void initItemTwo() {

        mItemTwoGridLayout = new GridLayoutManager(this, 6) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };

        mRvItemTwo.setLayoutManager(mItemTwoGridLayout);
        mItemTwoBallAdapter = new MyBallAdapter(null);
        mRvItemTwo.setAdapter(mItemTwoBallAdapter);

    }

    private void initItemOne() {


        mItemOneGridLayout = new GridLayoutManager(this, 6) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };

        mRvItemOne.setLayoutManager(mItemOneGridLayout);
        mItemOneBallAdapter = new MyBallAdapter(null);
        mRvItemOne.setAdapter(mItemOneBallAdapter);
    }

    private void initPopupWindowData() {
        mCenterPopWindow.setItemData(Arrays.asList(mCenterPopupData));
    }

    //这里主要是获取倒计时；
    private void requestIssueInfo(String type) {

        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("type",type);

        HttpManager.postAsyn(Constant_Url.ISSUE_INFO, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                DisPlay("网络异常！");
                e.printStackTrace();
            }

            @Override
            public void onResponse(String response) {
                try {

                    IssueInfoBean bean = FastOk.get(response, IssueInfoBean.class);
                    if(bean!=null){
                        setIssueInfoData(bean);
                    }else{
                        DisPlay("网络异常！");
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },paramsMap);

    }

    /**
     * 这里我们要做的一个操作就是显示多少期，以及还剩多长时间；
     *
     * @param bean
     */
    private void setIssueInfoData(IssueInfoBean bean) {
        String termNo = bean.getTermNo();         //当前多少期；
        String deadLine = bean.getDeadLine();    //截止时间；

        String term = termNo.substring(termNo.length() - 2);
        mTvTerm.setText("距" + term + "期截止");

        long deadline=0;
        try {
             deadline=Long.parseLong(deadLine);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        startCountDown(deadline * 1000);
    }

    //启动多长时间的定时器
    private void startCountDown(long time) {

        final CountDownTimer timer = new CountDownTimer(time, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {
                //这里的话， 我们对毫秒进行一个格式化的操作；

                mTvDate.setText(BaseUtils.formatDateLineToString(millisUntilFinished));
            }

            @Override
            public void onFinish() {
                //重新获取信息；
                requestIssueInfo(mType);
                this.cancel();
            }
        };
        timer.start();
    }

    /**
     * 获取遗漏和历史数据；
     */

    private void requestMissData(String type) {

        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("type",type);
        HttpManager.postAsyn(Constant_Url.GET_MISS_DATA, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                DisPlay("网络异常！");
            }

            @Override
            public void onResponse(String response) {
                try {
                    MissDataBean bean = FastOk.get(response, MissDataBean.class);
                    if (bean != null) {
                        setMissData(bean);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },paramsMap);

        /*OkHttpClientManager.Param Url = new OkHttpClientManager.Param("url", Constant_Url.GET_MISS_DATA);
        OkHttpClientManager.Param Type = new OkHttpClientManager.Param("type", type);
        OkHttpClientManager.Param[] param = new OkHttpClientManager.Param[]{Url, Type};
        try {
            OkHttpClientManager.getInstance().asynPost(new OnResultCallback() {
                @Override
                public void onGetResult(String json) {
                    MissDataBean bean = FastOk.get(json, MissDataBean.class);
                    setMissData(bean);
                }

                @Override
                public void onError() {
                    ToastUtil.showToast(BettingKLSFActivity.this, R.string.connect_failure);
                }
            }, param);
        } catch (IOException e) {
            e.printStackTrace();
        }*/
    }

    private void initBallData() {
        mListData20 = getListData(20);
        mListData18 = getListData(18);

        mListData2 = new ArrayList<>();
        mListData2.add("19");
        mListData2.add("20");

        mItemOneBallAdapter.refresh(mListData20);
        mItemTwoBallAdapter.refresh(mListData20);
    }

    public List<String> getListData(int number) {

        List<String> list = new ArrayList<>();
        for (int i = 0; i < number; i++) {
            int ballNumber = i + 1;
            list.add(ballNumber + "");
        }
        return list;
    }

    /**
     * 这里我们要做的一个操作就是获取遗漏和history数据；
     *
     * @param missData
     */
    public void setMissData(MissDataBean missData) {
        List<MissDataBean.Codes> codes = missData.getCodes();
        mHistoryAdapter.refresh(codes);
        mDrawerLayout.measureInnerLayout();

        if (missData.getOmission()!=null) {

            if(missData.getOmission().getM0()!=null){
                mM0 = missData.getOmission().getM0().split(",");
            }
            if(missData.getOmission().getM0()!=null){
                mM1 = missData.getOmission().getM1().split(",");
            }
            if(missData.getOmission().getM0()!=null){
                mM2 = missData.getOmission().getM2().split(",");
            }
            if(missData.getOmission().getM0()!=null){
                mM3 = missData.getOmission().getM3().split(",");
            }
            if(missData.getOmission().getM0()!=null){
                mM4 = missData.getOmission().getM4().split(",");
            }

        }
        mItemOneBallAdapter.refreshMissData(mM0);
    }

    public void setRandomChecked(List<String> datas, RecyclerView.LayoutManager layoutManager) {

        for (String data : datas) {
            int position = Integer.parseInt(data);
            View view = layoutManager.findViewByPosition(position);
            ((BallView) view.findViewById(R.id.bv_ball_view)).setChecked(true);
        }
    }

    /**
     * 实现机选的逻辑
     */
    public void randomSelected() {

        clearAllBallStatue();

        switch (mCurrentMode) {
            case 0:
                setRandomChecked(MakeRandomUtil.getBall(18), mItemOneGridLayout);
                break;
            case 1:
                setRandomChecked(MakeRandomUtil.getBall(2), mItemOneGridLayout);
                break;
            case 2:
                setRandomChecked(MakeRandomUtil.getWeiBall(20, 2), mItemOneGridLayout);
                break;
            case 3:
                setRandomChecked(MakeRandomUtil.getWeiBall(20, 3), mItemOneGridLayout);
                break;
            case 4:
                setRandomChecked(MakeRandomUtil.getWeiBall(20, 4), mItemOneGridLayout);
                break;
            case 5:
                setRandomChecked(MakeRandomUtil.getWeiBall(20, 5), mItemOneGridLayout);
                break;
            case 6:
                setRandomChecked(MakeRandomUtil.getWeiBall(20, 2), mItemOneGridLayout);
                break;
            case 7:
                LinkedList<String> weiBall = MakeRandomUtil.getWeiBall(20, 2);
                ArrayList<String> itemOne = new ArrayList<>();
                itemOne.add(weiBall.get(0));
                ArrayList<String> itemTwo = new ArrayList<>();
                itemTwo.add(weiBall.get(1));
                setRandomChecked(itemOne, mItemOneGridLayout);
                setRandomChecked(itemTwo, mItemTwoGridLayout);
                break;
        }
    }


    @Override
    protected boolean addBettingArea() {
        boolean canAdd = false;
        int betNum = 0;

        List<String> data1 = new ArrayList<>();
        List<String> data2 = new ArrayList<>();

        Map<String, Boolean> itemOneSelectBalls = mItemOneBallAdapter.getSelectBalls();
        Map<String, Boolean> itemTwoSelectBalls = mItemTwoBallAdapter.getSelectBalls();

        for (Map.Entry<String, Boolean> stringBooleanEntry : itemOneSelectBalls.entrySet()) {
            if (stringBooleanEntry.getValue()) {
                data1.add(stringBooleanEntry.getKey());
            }
        }
        for (Map.Entry<String, Boolean> stringBooleanEntry : itemTwoSelectBalls.entrySet()) {
            if (stringBooleanEntry.getValue()) {
                data2.add(stringBooleanEntry.getKey());
            }
        }

        switch (mCurrentMode) {
            case 0: //选一数投
            case 1:
                //选一红投
                if (data1.size() > 0) {
                    canAdd = true;
                    betNum = data1.size();
                }

                break;
            case 2:
                //任选二
                if (data1.size() > 1) {
                    canAdd = true;
                    betNum = BaseUtils.math2(data1.size(), 2);
                }
                break;
            case 3://任选三
                if (data1.size() > 2) {
                    canAdd = true;
                    betNum = BaseUtils.math2(data1.size(), 3);
                }
                break;
            case 4://任选四
                if (data1.size() > 3) {
                    canAdd = true;
                    betNum = BaseUtils.math2(data1.size(), 4);
                }
                break;
            case 5://任选五
                if (data1.size() > 4) {
                    canAdd = true;
                    betNum = BaseUtils.math2(data1.size(), 5);
                }
                break;
            case 6://选二连组
                if (data1.size() > 1) {
                    canAdd = true;
                    betNum = BaseUtils.math2(data1.size(), 2);
                }
                break;
            case 7://选二连直
                if (data1.size() > 0 && data2.size() > 0) {
                    canAdd = true;
                    betNum = data1.size() * data2.size();
                }
                break;
        }
        if (canAdd) {
            BettingBean bean = new BettingBean();
            bean.setIndex(mCurrentMode);
            bean.setData1(data1);
            bean.setData2(data2);
            bean.setBettingNumber(betNum);
            mBetList.add(bean);

            clearAllBallStatue();
            setBottomBarBettingNumber(mBetList.size());
        } else {
            DisPlay("至少选择一注！！！");
        }
        return false;
    }

    @Override
    protected void onBottonCircleRedDragged() {
        mBetList.clear();
        setBottomBarBettingNumber(mBetList.size());
    }

    @Override
    protected void onBottomRightButtonClick() {
        //这里对其进行一个判断；
        Map<String, Boolean> itemOneBalls = mItemOneBallAdapter.getSelectBalls();
        Map<String, Boolean> itemTwoBalls = mItemTwoBallAdapter.getSelectBalls();
        int itemOneSize=0;
        int itemTwoSize=0;

        for (Map.Entry<String, Boolean> stringBooleanEntry : itemOneBalls.entrySet()) {
            if (stringBooleanEntry.getValue()) {
                itemOneSize++;
            }
        }
        for (Map.Entry<String, Boolean> stringBooleanEntry : itemTwoBalls.entrySet()) {
            if (stringBooleanEntry.getValue()) {
                itemTwoSize++;
            }
        }
        if(itemOneSize>0 || itemOneSize>0){
            addBettingArea();
            jumpToBetConfirmActivity();
        }else if(mBetList.size()>0){
            //进行一个跳转
            jumpToBetConfirmActivity();
        }else{
            //机选一注
            randomSelected();
        }
    }

    public void jumpToBetConfirmActivity(){
        //接下来来我们要做的就是将BetList里面的数据进行一个转换；

        ArrayList<String> ballNumber = new ArrayList<>();   //条目上面的title
        ArrayList<String> mode = new ArrayList<>();         //条目下面的title;
        ArrayList<String> numMoney =new ArrayList<>();      //注数和金额；
        int totalMoney=0;
        int totalBettingNum=0;

        for (BettingBean bettingBean : mBetList) {
            //模式
            int index = bettingBean.getIndex();
            int bettingNumber=bettingBean.getBettingNumber();
            List<String> data1=null;
            List<String> data2=null;
            String ballNum="";

            if (bettingBean.getData1().size()>0) {
                data1=bettingBean.getData1();
            }
            if (bettingBean.getData2().size()>0) {
                data2=bettingBean.getData2();
            }

            if (data1 != null && data2!=null) {
                for (String s : data1) {
                    ballNum+=s+",";
                }
                ballNum=ballNum.substring(0,ballNum.length()-1);    //去掉最后一个，逗号

                ballNum+=" ";
                for (String s : data2) {
                    ballNum+=s+",";
                }
                ballNum=ballNum.substring(0,ballNum.length()-1);    //去掉最后一个，逗号
            }else if(data1!=null){
                //这里我们用空格分开；
                for (String s : data1) {
                    ballNum+=s+" ";
                }
                ballNum=ballNum.substring(0,ballNum.length()-1);    //去掉最后一个空格
            }

            String oneMode=mCenterPopupData[index];
            totalMoney+=bettingNumber*2;
            totalBettingNum+=bettingNumber;
            mode.add(oneMode);
            ballNumber.add(ballNum);
            numMoney.add(bettingNumber+"注 "+bettingNumber*2+"元");
        }

        Intent intent = new Intent(this, BetConfirmActivity.class);
        intent.putExtra("type", "gdklsf"); //彩种
        intent.putExtra("totalMoney", totalMoney); //总金额
        intent.putExtra("totalNum", totalBettingNum);//总注数f
        intent.putStringArrayListExtra("ballNumber", ballNumber); //球
        intent.putStringArrayListExtra("mode", mode); //玩法及模式
        intent.putStringArrayListExtra("numMoney", numMoney); //注数及金额
        startActivityForResult(intent, 0);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        Intent intent = data;
        Bundle extras = intent.getExtras();
        int totalMoney = intent.getIntExtra("totalMoney", 0); //总金额
        int totalBettingNum = intent.getIntExtra("totalNum", 0);   //总注数
        ArrayList<String> selectedNumbers = intent.getStringArrayListExtra("ballNumber"); //球
        ArrayList<String> playModes = intent.getStringArrayListExtra("mode"); //玩法
        ArrayList<String> bettingNums = intent.getStringArrayListExtra("numMoney"); //注数及金额
        //我们是需要将数据，还原回去。。
        ArrayList<BettingBean> list=new ArrayList<>();

        List<String> indexType = Arrays.asList(KlpkUtils.indexType);

        if (selectedNumbers!=null && playModes!=null &&bettingNums!=null) {

            for (int i = 0; i < playModes.size(); i++) {

                BettingBean bettingBean = new BettingBean();
                List<String> data1=new ArrayList<>();
                List<String> data2=new ArrayList<>();

                String playMode = playModes.get(i);
                String selectedNumberStr = selectedNumbers.get(i);  // 这样的数据：2 3 9   2，3，9  3，2
                String bettings = bettingNums.get(i);   //多少注、多少元

                if(bettings.indexOf(",")==-1){
                    //这里我们要判断一下是否有","
                    String[] selectedNumberArray = selectedNumberStr.split(" ");
                    data1.addAll(Arrays.asList(selectedNumberArray));
                }else{
                    String[] items= selectedNumberStr.split(" ");
                    data1.addAll(Arrays.asList(items[0].split(",")));
                    data2.addAll(Arrays.asList(items[1].split(",")));
                }
                String betNumStr = bettings.substring(0, bettings.indexOf("注"));

                bettingBean.setData1(data1);
                bettingBean.setData2(data2);
                bettingBean.setIndex(Arrays.asList(mCenterPopupData).indexOf(playMode));
                bettingBean.setBettingNumber(Integer.parseInt(betNumStr));
                list.add(bettingBean);
            }
        }
        mBetList=list;
        setBottomBarBettingNumber(mBetList.size());
    }


    @Override
    protected void onBottonLeftButtonClick() {
        String text = getBottomBarleftText();
        if ("机选".equals(text)) {
            //随机选中一个
            randomSelected();
            setBottomBarLeftText("清空");
        } else {
            //清空逻辑；
            clearAllBallStatue();
            setBottomBarLeftText("机选");
        }
    }


    @Override
    protected void sendRandom(Intent intent) {

        mBetList.clear();
        //机选
        int num = intent.getIntExtra("num", 0);
        if (num > 0) {
            clearAllBallStatue();
            //开始机选
            for (int i = 0; i < num; i++) {
                randomSelected();
                addBettingArea();
            }

            ArrayList<String> ballNumber = new ArrayList<>();   //条目上面的title
            ArrayList<String> mode = new ArrayList<>();         //条目下面的title;
            ArrayList<String> numMoney =new ArrayList<>();      //注数和金额；
            int totalMoney=0;
            int totalBettingNum=0;

            for (BettingBean bettingBean : mBetList) {
                //模式
                int index = bettingBean.getIndex();
                int bettingNumber=bettingBean.getBettingNumber();
                List<String> data1=null;
                List<String> data2=null;
                String ballNum="";

                if (bettingBean.getData1().size()>0) {
                    data1=bettingBean.getData1();
                }
                if (bettingBean.getData2().size()>0) {
                    data2=bettingBean.getData2();
                }

                if (data1 != null && data2!=null) {
                    for (String s : data1) {
                        ballNum+=s+",";
                    }
                    ballNum=ballNum.substring(0,ballNum.length()-1);    //去掉最后一个，逗号

                    ballNum+=" ";
                    for (String s : data2) {
                        ballNum+=s+",";
                    }
                    ballNum=ballNum.substring(0,ballNum.length()-1);    //去掉最后一个，逗号
                }else if(data1!=null){
                    //这里我们用空格分开；
                    for (String s : data1) {
                        ballNum+=s+" ";
                    }
                    ballNum=ballNum.substring(0,ballNum.length()-1);    //去掉最后一个空格
                }

                String oneMode=mCenterPopupData[index];
                totalMoney+=bettingNumber*2;
                totalBettingNum+=bettingNumber;
                mode.add(oneMode);
                ballNumber.add(ballNum);
                numMoney.add(bettingNumber+"注 "+bettingNumber*2+"元");
            }

            intent.setAction(Constant_Result.EXECRANDOMLOTTERYNUM);
            intent.putExtra("type", "gdklsf"); //彩种
            intent.putExtra("totalMoney", totalMoney); //总金额
            intent.putExtra("totalNum", totalBettingNum);//总注数f
            intent.putStringArrayListExtra("ballNumber", ballNumber); //球
            intent.putStringArrayListExtra("mode", mode); //玩法及模式
            intent.putStringArrayListExtra("numMoney", numMoney); //注数及金额
            sendBroadcast(intent);
        }
    }
}
